package com.im.server.general.common.app;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.im.server.general.manage.auth.manager.AuthManager;


/**
 * 描述：
 * 
 * @author XiaHui
 * @date 2015年12月19日 下午12:57:36
 * @version 0.0.1
 */
public class UserContextResolver implements HandlerMethodArgumentResolver {

	@Resource
	AuthManager authManager;
	
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterType() == UserContext.class;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		String token = request.getHeader("X-Token");
		String userId=authManager.getUserId(token);
		Class<?> clazz = parameter.getParameterType();
		Object object = clazz.newInstance();
		BeanWrapper beanWrapper = new BeanWrapperImpl(object);
		beanWrapper.setPropertyValue("currentUserId", userId);
		beanWrapper.setPropertyValue("token", token);
		return object;
	}
}
